//
//  HMComposeView.swift
//  Black22
//
//  Created by Apple on 16/11/24.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import pop

//  罩层视图
class HMComposeView: UIView {

    //  目标控制器
    var target: UIViewController?
    //  背景视图
    private lazy var bgImageView: UIImageView = UIImageView(image: self.getScreenShot().applyLightEffect())
    //  6个菜单按钮
    private lazy var composeButtonsArray: [HMComposeButton] = [HMComposeButton]()
    //  plist数据
    private lazy var composeModelArray: [HMComposeMenu] = self.loadComposePlistData()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        self.size = CGSize(width: ScreenWidth, height: ScreenHeight)
        
        addSubview(bgImageView)
        
        //  添加子按钮
        addChildButton()
        
        startAnimation(isUp: true)
        
    }
    
    private func addChildButton() {
    
        let buttonWidth: CGFloat = 80
        let buttonHeight: CGFloat = 110
        //  间距
        let itemMargin: CGFloat = (width - 3 * buttonWidth) / 4
        
        //  添加按钮
        for i in 0..<6 {
        
            //  列的索引
            let colIndex = i % 3
            //  行的索引
            let rowIndex = i / 3
            
        
            
            let button = HMComposeButton()
            button.tag = i
            button.addTarget(self, action: #selector(btnAction(btn:)), for: .touchUpInside)
            button.frame.origin.x = CGFloat(colIndex) * buttonWidth + CGFloat(colIndex + 1) * itemMargin
            button.frame.origin.y = CGFloat(rowIndex) * buttonHeight + CGFloat(rowIndex) * itemMargin + ScreenHeight
            //  获取模型
            let model = composeModelArray[i]
            button.setTitle(model.title, for: .normal)
            button.setImage(UIImage(named: model.icon!), for: .normal)
            button.size = CGSize(width: buttonWidth, height: buttonHeight)
            
            addSubview(button)
            composeButtonsArray.append(button)
        }
        
        
        
    }
    
    // MARK:    -点击事件
    @objc private func btnAction(btn: HMComposeButton) {
        UIView.animate(withDuration: 0.25, animations: {
            for button in self.composeButtonsArray {
                button.alpha = 0.2
                if button == btn {
                    button.transform = CGAffineTransform(scaleX: 2, y: 2)
                } else {
                    button.transform = CGAffineTransform(scaleX: 0.2, y: 0.2)
                }
            }
            
        }, completion: { (_)->() in
            
            UIView.animate(withDuration: 0.24, animations: { 
                for button in self.composeButtonsArray {
                    button.alpha = 1
                    button.transform = CGAffineTransform.identity
                }
            }, completion: { (_) in
                //  弹出控制器
//                let composeVc = HMComposeViewController()
//                self.target?.present(composeVc, animated: true, completion: { 
//                    self.removeFromSuperview()
//                })
                
                
                let model = self.composeModelArray[btn.tag]
                //  通过字符串类名获取类实例
                let classType = NSClassFromString(model.className!) as! HMComposeViewController.Type
                let vc = classType.init()
                let nav = HMNavigationViewController(rootViewController: vc)
                self.target?.present(nav, animated: true, completion: {
                    self.removeFromSuperview()
                })
                
                
                
            })

        })
        
        
    }
    
    //  读取plist文件数据
    fileprivate func loadComposePlistData() -> [HMComposeMenu] {
    
        let path = Bundle.main.path(forResource: "compose.plist", ofType: nil)!
        let dicArray = NSArray(contentsOfFile: path) as! [[String: Any]]
        //  字典转模型
        let modleArray = NSArray.yy_modelArray(with: HMComposeMenu.self, json: dicArray) as! [HMComposeMenu]
        return modleArray
    }
    
    // MARK:    -开启动画
    private func startAnimation(isUp: Bool) {
        
        if isUp == false {
            //  数组翻转
            composeButtonsArray = composeButtonsArray.reversed()
        }
        
        for (i, button) in composeButtonsArray.enumerated() {
            let popAnimation = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            if isUp {
                //  动画目的地
                popAnimation?.toValue = NSValue(cgPoint: CGPoint(x: button.centerX, y: button.centerY - 350))
            } else {
                //  动画目的地
                popAnimation?.toValue = NSValue(cgPoint: CGPoint(x: button.centerX, y: button.centerY + 350))
            }
            
            //  初始速度
            popAnimation?.springSpeed = 10
            //  弹簧幅度
            popAnimation?.springBounciness = 10
            //  开始时间-> 动画的间隔时间
            popAnimation?.beginTime = CACurrentMediaTime() + Double(i) * 0.025
            
            //  执行动画
            button.pop_add(popAnimation, forKey: nil)
            
            
            
        }
        
        
        
    }
    
    
    //  截图
    func getScreenShot() -> UIImage {
    
        let window = UIApplication.shared.keyWindow!
        UIGraphicsBeginImageContext(window.size)
        //  渲染到window
        window.drawHierarchy(in: CGRect(origin: CGPoint.zero, size: window.size), afterScreenUpdates: false)
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return image!
    }
    
    
    //  添加视图
    func show(target: UIViewController) {
        self.target = target
        
//        let window = UIApplication.shared.windows.last!
//        window.addSubview(self)
        self.target?.view.addSubview(self)
    }
    
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        
        startAnimation(isUp: false)
        
        //  延时0.3秒删除
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.3, execute: {
            self.removeFromSuperview()
        })
        
        
    }
    
    
}
